package com.demo.function.spring.httpinterface.config;

import com.demo.function.spring.httpinterface.RestClientMiyaHttpInterfaceClient;
import com.demo.function.spring.httpinterface.WebClientMiyaHttpInterfaceClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

/**
 * Spring 6新功能HTTP Interface，该功能替代OpenFeign。
 * OpenFeign进入维护模式，不再有新功能。<br>
 * HTTP Interface目前发现无法接入注册中心，无法实现服务发现功能（2025.03.27）。配合k8s的svc可以解决服务发现问题
 */
@Configuration
public class HttpInterfaceConfig {

    /**
     * 创建 HttpServiceProxy，底层使用webClient
     * @return HttpServiceProxyFactory对象
     */
    @Bean
    public HttpServiceProxyFactory webClientHttpServiceProxyFactory() {
        // 创建客户端
        WebClient webClient = WebClient.builder().build();
        WebClientAdapter adapter = WebClientAdapter.create(webClient);
        return HttpServiceProxyFactory.builderFor(adapter).build();
    }

    @Bean
    public WebClientMiyaHttpInterfaceClient webClientMiyaHttpInterfaceClient(HttpServiceProxyFactory webClientHttpServiceProxyFactory) {
        return webClientHttpServiceProxyFactory.createClient(WebClientMiyaHttpInterfaceClient.class);
    }

    /**
     * 创建 HttpServiceProxy，底层使用restClient
     * @return HttpServiceProxyFactory对象
     */
    @Bean
    public HttpServiceProxyFactory restClienthttpServiceProxyFactory() {
        // 创建客户端
        RestClient restClient = RestClient.builder().build();
        RestClientAdapter adapter = RestClientAdapter.create(restClient);
        return HttpServiceProxyFactory.builderFor(adapter).build();
    }

    @Bean
    public RestClientMiyaHttpInterfaceClient restClientMiyaHttpInterfaceClient(HttpServiceProxyFactory restClienthttpServiceProxyFactory) {
        return restClienthttpServiceProxyFactory.createClient(RestClientMiyaHttpInterfaceClient.class);
    }
}
